﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using SMSSnew.DATA;
using Telerik.WebControls.Base.Calendar;
 
namespace SMSSnew.UI
{
    public partial class FullDayLeave : System.Web.UI.Page
    {
        public static string userName; 
        LeaveApplicationListDA leaveAppList = new LeaveApplicationListDA();
        LeaveApplicationDA leaveApp = new FullDayLeaveDA();
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                userName = Session["username"].ToString();
                setAvailablePendingLeavesInLabels();
                radDpFrom.SelectedDates.Clear();
            }
        }

       
        //count medical and casual leaves taken by the teacher previously and display available leaves
        //ok can be used for half/short/special
        protected void setAvailablePendingLeavesInLabels()
        {
 
            DateTime currentDate = new DateTime();
            currentDate = DateTime.Now;
            string numOfLeaves;

            numOfLeaves = leaveAppList.countAvailableAndPendingLeaves(userName);
            string[] amountOfLeaves = numOfLeaves.Split(new string[] { "," }, StringSplitOptions.None);

            lblAvailCasualNo.Text = (Math.Truncate( Double.Parse(amountOfLeaves[0]))).ToString();
            lblAvailMedicalNo.Text = (Math.Truncate(Double.Parse(amountOfLeaves[1]))).ToString();
            lblPendCasualNo.Text = (Math.Round(Double.Parse(amountOfLeaves[2]))).ToString();
            lblPendMedicalNo.Text = (Math.Round(Double.Parse(amountOfLeaves[3]))).ToString();
            lblPendDutyNo.Text = (Math.Round(Double.Parse(amountOfLeaves[4]))).ToString();
            lblPendNopayNo.Text = (Math.Round(Double.Parse(amountOfLeaves[5]))).ToString();

            lblYear.Text = currentDate.Year.ToString();
        }


        // 2013.08.07
        protected void butSubmit_Click(object sender, EventArgs e)
        {
            // validate whether the form is filled or not
            if (countDurationBetweenTwoDays() < 1)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Please fill the form correctly');", true);
            }
            else
            {
                setValuesToLeaveApp();
                leaveApp.addLeaveToDB(leaveApp);
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('Requesting is successfull');", true);
                radDpFrom.SelectedDates.Clear();
                txtReason.Text = "";
                setAvailablePendingLeavesInLabels();
                Response.Redirect("LeaveHome.aspx");
            }
          
        }

        // have to sort selected dates by the user
        protected void sortSelectedDaysOfCalendar()
        {
            DateTime temp = new DateTime();

            for (int pass = 1; pass <= radDpFrom.SelectedDates.Count - 1; pass++)
            {
                for (int i = 0; i <= radDpFrom.SelectedDates.Count - 2; i++)
                {
                    if ((radDpFrom.SelectedDates[i]).Date > (radDpFrom.SelectedDates[i+1]).Date)
                    {
                        temp = (radDpFrom.SelectedDates[i+1].Date);
                        (radDpFrom.SelectedDates[i + 1].Date) = (radDpFrom.SelectedDates[i].Date);
                        (radDpFrom.SelectedDates[i].Date) = temp;
                        
                    }
                }
            }
        }

        // setting values to leaveAppFrom object
        protected void setValuesToLeaveApp()
        {
            DateTime start = new DateTime();
            DateTime end = new DateTime();

            sortSelectedDaysOfCalendar();
            start = radDpFrom.SelectedDate.Date;

            for (int i = 0; i < radDpFrom.SelectedDates.Count; i++)
            {
                end = (radDpFrom.SelectedDates[i]).Date;
            }

            leaveApp.setStartDate(start);
            leaveApp.setTeacherID(userName);
            leaveApp.setEndDate(end);
            leaveApp.setDuration(Double.Parse(countDurationBetweenTwoDays().ToString()));
            leaveApp.setReason(txtReason.Text);
            leaveApp.setStatus(0);
            leaveApp.setLeaveID("");
            leaveApp.setleaveCategoryId("FULL");
            leaveApp.setAbsentTimePeriod("7.30-1.30");

            if (comLeaveType.SelectedValue == "Medical Leaves")
                leaveApp.setleaveTypeId("MED");
            else if (comLeaveType.SelectedValue == "Casual Leaves")
                leaveApp.setleaveTypeId("CAS");
            else if (comLeaveType.SelectedValue == "Duty Leaves")
                leaveApp.setleaveTypeId("DUT");
            else if (comLeaveType.SelectedValue == "No Pay Leaves")
                leaveApp.setleaveTypeId("NOP");
            
        }


        //ok
        protected void imgBtnBack_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("LeaveHome.aspx");
        }

    
        // ok, when change dropdown clear the calendar
        protected void comLeaveType_SelectedIndexChanged(object sender, EventArgs e)
        {
            radDpFrom.SelectedDates.Clear();
            txtReason.Text = "";
        }

        
        // to disable weekend days in calendar
        //ok
        protected void radDpFrom_DayRender(object sender, Telerik.Web.UI.Calendar.DayRenderEventArgs e)
        {
            if (e.Day.IsWeekend)
            {
                e.Cell.Style["display"] = "none";
            }
        }

        // to disable weekend days in calendar
        //ok
        protected void radDpFrom_HeaderCellRender(object sender, Telerik.Web.UI.Calendar.HeaderCellRenderEventArgs e)
        {
            string columnName = e.Cell.Text;
            // the name of the column depends of the calendar Culture and the set DayNameFormat 
            if (columnName == "S")
            {
                e.Cell.Style["display"] = "none";
            }
        }

        // count duration between two days
        protected int countDurationBetweenTwoDays()
        {
            DateTime start = new DateTime();
            DateTime end = new DateTime();

            sortSelectedDaysOfCalendar();
            start = radDpFrom.SelectedDate.Date;

            for (int i = 0; i < radDpFrom.SelectedDates.Count; i++)
            {
                end = (radDpFrom.SelectedDates[i]).Date;
            }

            //  string message = leaveApp.countDurationBetweenTwoDays(start, end, userName).ToString();
            return leaveApp.countDurationBetweenTwoDays(start, end, userName);
        }
        
        // all selecting dates are validating asap in this method, it containing ajax client side validations
        protected void radDpFrom_SelectionChanged(object sender, Telerik.Web.UI.Calendar.SelectedDatesEventArgs e)
        {
            string message;
            DateTime date = new DateTime(); 

            // to set the last selected date for the validations
            for (int i = 0; i < e.SelectedDates.Count; i++)
            {
                 date = (e.SelectedDates[i]).Date;
            }

            // validate selected date is greater than today
            if (leaveApp.validateRequstedDateGreaterThanToday(date) != "")
            {
                message = leaveApp.validateRequstedDateGreaterThanToday(date);
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + message + "');", true);
                radDpFrom.SelectedDates.Clear();
            }
            
            // validate whether selected date is a holiday
            else if (leaveApp.validateWhetherHoliDay(date) != "")
            {
                message = leaveApp.validateWhetherHoliDay(date);
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + message + "');", true);
                radDpFrom.SelectedDates.Clear();
            }
            // validate whether requesting already requested days
            else if (leaveApp.validateLeaveRequestedEarlier(date, userName) != "")
            {
                message = leaveApp.validateLeaveRequestedEarlier(date, userName);
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + message + "');", true);
                radDpFrom.SelectedDates.Clear();
            }
            // validate whether exceeding requesting medical leaves in row
            else if (radDpFrom.SelectedDates.Count > 2 && comLeaveType.SelectedValue == "Medical Leaves")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('You can request only two medical leaves in row');", true);
                radDpFrom.SelectedDates.Clear();
            }
            // validate whether exceeding requesting casual leaves in row
            else if (radDpFrom.SelectedDates.Count > 6 && comLeaveType.SelectedValue == "Casual Leaves")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('You can request only six casual leaves in row');", true);
                radDpFrom.SelectedDates.Clear();
            }
            // validate whether exceeding maximum medical leaves for year
            else if ((radDpFrom.SelectedDates.Count + Int32.Parse(lblPendMedicalNo.Text.ToString())) > (Int32.Parse(lblAvailMedicalNo.Text.ToString())) && comLeaveType.SelectedValue == "Medical Leaves")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('You have exceeded the offered medical leaves');", true);
                radDpFrom.SelectedDates.Clear();
            }
            // validate whether exceeding maximum casual leaves for year
            else if ((radDpFrom.SelectedDates.Count + Int32.Parse(lblPendCasualNo.Text.ToString())) > (Int32.Parse(lblAvailCasualNo.Text.ToString())) && comLeaveType.SelectedValue == "Casual Leaves")
            {
                ClientScript.RegisterStartupScript(this.GetType(), "", "alert('You have exceeded the offered casual leaves');", true);
                radDpFrom.SelectedDates.Clear();
            }  
        }

        protected void butViewSummary_Click(object sender, EventArgs e)
        {
            Response.Redirect("LeaveHome.aspx");
        }

        protected void lnkButSummary_Click(object sender, EventArgs e)
        {
            Response.Redirect("LeaveHome.aspx");
        }

   

         

       

      
    }
}
